"""
API场景组合测试工具 - 打包脚本
"""
import os
import sys
import shutil
import subprocess

def build_executable():
    """构建可执行文件"""
    print("开始构建可执行文件...")
    
    # 确保目录存在
    if not os.path.exists('dist'):
        os.makedirs('dist')
    
    # 使用PyInstaller打包
    cmd = [
        'pyinstaller',
        '--name=API场景组合测试工具',
        '--icon=app/static/favicon.ico',
        '--add-data=app/templates;app/templates',
        '--add-data=app/static;app/static',
        '--hidden-import=playwright',
        '--hidden-import=flask_sqlalchemy',
        '--onefile',
        '--windowed',
        'app/main.py'
    ]
    
    # 根据操作系统调整命令
    if sys.platform.startswith('win'):
        cmd[3] = '--add-data=app/templates;app/templates'
        cmd[4] = '--add-data=app/static;app/static'
    else:
        cmd[3] = '--add-data=app/templates:app/templates'
        cmd[4] = '--add-data=app/static:app/static'
    
    # 执行打包命令
    try:
        subprocess.run(cmd, check=True)
        print("可执行文件构建成功！")
    except subprocess.CalledProcessError as e:
        print(f"构建失败: {e}")
        return False
    
    return True

def install_playwright_browsers():
    """安装Playwright浏览器"""
    print("安装Playwright浏览器...")
    try:
        subprocess.run(['playwright', 'install', 'chromium'], check=True)
        print("Playwright浏览器安装成功！")
    except subprocess.CalledProcessError as e:
        print(f"Playwright浏览器安装失败: {e}")
        return False
    
    return True

def main():
    """主函数"""
    # 安装依赖
    print("安装依赖...")
    subprocess.run(['pip', 'install', '-r', 'requirements.txt'], check=True)
    
    # 安装Playwright浏览器
    if not install_playwright_browsers():
        return
    
    # 构建可执行文件
    if not build_executable():
        return
    
    print("构建完成！可执行文件位于 dist 目录中。")

if __name__ == '__main__':
    main()